package wangjg.commons.io.file;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import android.util.Log;
/**
 * 
 * @author wangjg
 *
 */
public class FileUtil {
	
	public static void delete(File file){
		if(file.isFile()){
			boolean b = file.delete();
			Log.d("delete ",file.getPath()+",b="+b+",canWrite="+file.canWrite());
			return;
		}else if(file.isDirectory()){
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				delete(files[i]);
			}
			file.delete();
		}
	}

	public static long getFileTotal(File dir,Pattern p){
		long total=0;
		File[] files=dir.listFiles();
		for(int i=0;i<files.length;i++){
			if(files[i].isFile()){
				if(p!=null && !p.matcher(files[i].getName()).matches()){
					continue;
				}
				total++;
			}else if(files[i].isDirectory()){
				total+=getFileTotal(files[i],p);
			}
		}
		return total;
	}
	
	/**
	 * 
	 * @param extname .txt
	 * @return
	 */
	public static FileFilter getFileFilter(String extname){
		return new FileFilterImpl(extname);
	}
	
	public static FilenameFilter getFilenameFilterImpl(String extname){
		return new FilenameFilterImpl(extname);
	}

	public static long getFileTotal(String path,String filterReg) {
		Pattern p = Pattern.compile(filterReg);
		return getFileTotal(new File(path),p);
	}
	
	public static String getExtName(String path){
		String extname1 = null;
		int i=path.lastIndexOf(".");
		if(i!=-1){
			extname1=path.substring(i,path.length());
		}
		return extname1;
	}
}


class FileFilterImpl implements FileFilter{

	private String extname;

	public FileFilterImpl(String extname) {
		this.extname=extname;
	}

	public boolean accept(File pathname) {
		String extname1 = null;
		String path=pathname.getPath();
		int i=path.lastIndexOf(".");
		if(i!=-1){
			extname1=path.substring(i,path.length());
			System.out.println(extname1);
			return this.extname.equals(extname1);
		}else{
			return this.extname==extname1;
		}
	}
	
}

class FilenameFilterImpl implements FilenameFilter{

	private String extname;

	public FilenameFilterImpl(String extname) {
		this.extname=extname;
	}

	public boolean accept(File dir, String name) {
		if(!dir.exists()){
			//return false;
		}
		String extname1 = null;
		String path = name;
		int i = path.lastIndexOf(".");
		if(i!=-1){
			extname1=path.substring(i,path.length());
			return this.extname.equals(extname1);
		}else{
			return this.extname==extname1;
		}
	}
	
}